package com.redrose.rxandroiddemo.camera;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;

import com.google.common.util.concurrent.ListenableFuture;

public class MyPreviewView extends PreviewView {

    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private ImageCapture mImageCapture;

    public MyPreviewView(Context context) {
        super(context);
    }

    public MyPreviewView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyPreviewView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void startCamera() {
        cameraProviderFuture = ProcessCameraProvider.getInstance(getContext());
        cameraProviderFuture.addListener(mRunnable, ContextCompat.getMainExecutor(getContext()));
    }

    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                //将相机的生命周期和activity的生命周期绑定，camerax 会自己释放，不用担心了
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                //预览的 capture，它里面支持角度换算
                Preview preview = new Preview.Builder().build();

                //创建图片的 capture
                mImageCapture = new ImageCapture.Builder()
                        .setFlashMode(ImageCapture.FLASH_MODE_AUTO)
                        .build();


                //选择后置摄像头
                CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();

                //预览之前先解绑
                cameraProvider.unbindAll();

                //将数据绑定到相机的生命周期中
                Camera camera = cameraProvider.bindToLifecycle(getActivityFromView(MyPreviewView.this), cameraSelector, preview, mImageCapture);
                //将previewview 的 surface 给相机预览
                preview.setSurfaceProvider(createSurfaceProvider(camera.getCameraInfo()));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private AppCompatActivity getActivityFromView(View view) {
        Context context = view.getContext();
        while (context instanceof ContextWrapper) {
            if (context instanceof AppCompatActivity) {
                return (AppCompatActivity) context;
            }
            context = ((ContextWrapper) context).getBaseContext();
        }
        return null;
    }
}
